﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ledict.ConditionExtract.Common;
using Ledict.ConditionExtract.Enum;
using Ledict.ConditionExtract.Model;
using Ledict.Utility.Extension;
using Ledict.Utility.Helper;
using System.Data;
using System.Threading;

namespace Ledict.ConditionExtract.BLL.WorkProcess
{
    /// <summary>
    ///  dcy 2017/3/9 
    ///  由于需求变动及其逻辑方面的变动
    ///  故重新设计民事匹配规则
    /// </summary>
    public class WorkThread_Civil : WorkThread_first
    {
        #region 全局变量
        /// <summary>
        ///  匹配出来的数据集合
        /// </summary>
        private List<Model.RuleNode> liMatch = new List<Model.RuleNode>();

        /// <summary>
        /// 组合下，剔除的数据id
        /// </summary>
        private List<string> outMatch = new List<string>();
        /// <summary>
        ///  标记是够为组合标签（与单一规则不同）
        /// </summary>
        private bool iszuhe = false;
        /// <summary>
        /// 处理总数
        /// </summary>
        public int MaxCount = 0; //处理总数
        /// <summary>
        /// 处理当前数量
        /// </summary>
        private int CurrentCount = 0; //处理当前数量
        /// <summary>
        ///  匹配规则的父级，如果子级不匹配。则存入父级
        /// </summary>
        private Model.RuleNode Prulemodel = new RuleNode();
        /// <summary>
        ///  正则dll接口
        /// </summary>
        protected RegexParse.RegexParse getregex = new RegexParse.RegexParse();
        /// <summary>
        /// 规则案由树操作类
        /// </summary>
        protected TreeDataBLL trbll = new TreeDataBLL();
        /// <summary>
        ///  节点（案由）逻辑操作类
        /// </summary>
        protected WorkThread_Public work = new WorkThread_Public();
        /// <summary>
        /// config配置是否为组合标签
        /// </summary>
        private string strOneAndCombination = ConfigHelper.AppSettings("CivilMatchOneAndCombination");
        /// <summary>
        ///  静态变量类集合
        /// </summary>
        private StaticCacheBLL staticcache = new StaticCacheBLL();
        /// <summary>
        ///  匹配文本存放操作类
        /// </summary>
        protected Express_WordBLL wordbll = new Express_WordBLL();
        /// <summary>
        /// 创建主键
        /// </summary>
        private NewIDBLL newid = new NewIDBLL();
        #endregion

        #region 对外方法，准备数据
        public override void execute_Start()
        {
            //打开缓存
            getregex.StartCatch();
            //查询案由的案由路径
            conditon.HeadwordId = trbll.GetHeadWordAllPid(conditon.HeadwordId);
            MaxCount = 0;
            CurrentCount = 0;
            //2、待处理的数据
            MaxCount += GetDataSourceCount(conditon);

            // 没数据结束进度条
            if (MaxCount == 0) //没有可以跑数据的案例
            {
                if (MaxCount >= CurrentCount)
                {
                    processShow(MaxCount, CurrentCount);
                }
            }
            else //加工数据
            {
                execute_Condition(conditon);
            }
            //关闭缓存
            getregex.EndCatch();
        }
        #endregion

        #region 跑数据开始，逻辑处理
        public virtual void execute_Condition(DataSourceCondition condition) //案由ID
        {
            int perPage = condition.SearchPerSize; //每次从索引取5000条
            int page = (int)Math.Ceiling((double)MaxCount / perPage); //多少页
            DataTable caseiddt; //分页数据源集合
            // 选择的案由开始位置
            DataTable processNodedt = work.CivilBelongCaseCauseId(condition.SituationId);

            #region 循环处理每页案例
            for (int pag = 1; pag <= page; pag++)
            {

                //1.由“查询条件”（condition）查询lucene索引，得到“表述”
                // 获取每页案例的详细内容
                caseiddt = GetDataSource(condition, pag, perPage); //案由ID的相关文本数据(得到Caseid)
                IEnumerable<DataRow> caseidenumerable = caseiddt.Rows.Cast<DataRow>();

                int indextemp = -1; // 设置索引开始位置

                Parallel.ForEach(caseidenumerable, new ParallelOptions
               {
                   MaxDegreeOfParallelism = 1
               }, row =>
               {
                   int k = Interlocked.Add(ref indextemp, 1); // 得到当前索引
                   liMatch = new List<RuleNode>(); //清空数据集每个案例
                   outMatch = new List<string>();
                   string processCCId = processNodedt.Rows[0]["CC_ID"].ToString(); //节点开始处
                   string processNodeName = processNodedt.Rows[0]["CC_Name"].ToString();
                   if (k == 0) //添加组合单一节点
                   {
                       work.AddMatch_virtual("S" + processCCId, "单一");
                       if (processNodeName.Contains("争议焦点要素"))
                       {
                           work.AddMatch_virtual("M" + processCCId, "组合");
                       }
                   }
                   DisposeEveyCase(caseiddt.Rows[k], condition, k); //处理每个案例
                   #region 处理完成后,进度条

                   CurrentCount++; // 显示进度条
                   if (MaxCount >= CurrentCount)
                   {
                       processShow(MaxCount, CurrentCount);
                   }

                   int innercurrentcout = Interlocked.Add(ref this.CurrentCount, 1);
                   if (this.MaxCount >= innercurrentcout)
                   {
                       this.processShow(this.MaxCount, innercurrentcout);
                   }

                   lockObj.WaitOne();
                   if (readyToClose)
                   {
                   }

                   #endregion 处理完成后,进度条
               });
            }
            #endregion
        }

        /// <summary>
        ///  每个案例的处理
        /// </summary>
        /// <param name="dw"></param>
        /// <param name="k"></param>
        /// <param name="condition"></param>
        private bool DisposeEveyCase(DataRow dr, DataSourceCondition condition,int k)
        {
            DataTable conditiondt; //节点信息集合
            #region 取出案例相关信息
            string paragraphTypeId = dr["ParagraphTypeId"].ToString();
            string id = dr["id"].ToString();
            string caseid = dr["CaseId"].ToString();
            string paragraphText = dr["ParagraphText"].ToString();
          //  paragraphText = dr["ParagraphText"].ToString();
            if (caseid != "4817542")
            {
                return true;
            }
            paragraphText = "本院认为：华隆公司与郑有兴签订的前期物业管理服务协议，系其真实意思表示，内容亦不违反法律、行政法规禁止性规定，该合同合法有效，当事人应当遵循诚实信用原则按照约定履行自己的义务。本案的争议焦点有：1.郑有兴应以什么标准向华隆公司支付物业管理服务费，华隆公司主张郑有兴向其支付违约金的诉求能否得到支持，原告与天津市河北区金田公寓业主会签订的《天津市住宅物业服务合同》合法有效，应予认定；";
            #endregion

            #region 提取开始规则节点
            DataTable processNodedt = work.CivilBelongCaseCauseId(condition.SituationId);
            string processCCId = processNodedt.Rows[0]["CC_ID"].ToString(); //节点开始处
            string processNodeName = processNodedt.Rows[0]["CC_Name"].ToString();
            #endregion

            #region 如果前端选择包含开始节点
            bool flog = false; // 开始节点是否符合规则
            if (condition.IsHasOwnNode)// 选择包含本节点
            {
                var currentDt = staticcache.GetCurrentCivilHeadwordData(condition.SituationId, condition.OperatePurposeId,
              condition.OperateParagraphId, true); // 获取节点要匹配的正则

                if (currentDt != null && currentDt.Rows.Count > 0 && Convert.ToInt32(currentDt.Rows[0]["RegCount"].ToString()) > 0)//有正则
                {
                    flog = IsMatch(paragraphText, currentDt.Rows[0]["CC_RegexInfoCode"].ToString()) > 0;
                }
                if (flog)
                {
                    Model.RuleNode model = new RuleNode();
                    model.cc_id = processCCId;
                    model.cc_name = processNodeName;
                    model.regxStr = strMatch(paragraphText, currentDt.Rows[0]["CC_RegexInfoCode"].ToString());
                    model.caseid = caseid;
                    liMatch.Add(model);
                }
            }
            #endregion

            #region 如果不包含开始节点。开始匹配开始节点的第一子集（包含开始匹配第一子集）
            if ((condition.IsHasOwnNode && flog) || !condition.IsHasOwnNode)
            {
                conditiondt = staticcache.GetCivilHeadwordData(processCCId, condition.OperatePurposeId,
                  condition.OperateParagraphId);
                if (string.IsNullOrEmpty(strOneAndCombination)) //为空只跑单一规则
                {
                    ExecuteMatchOne(paragraphText, caseid, paragraphTypeId, processCCId, conditiondt);
                }else
                {
                    var strArray = strOneAndCombination.Split(new string[] { "," },
                                        StringSplitOptions.RemoveEmptyEntries);
                    //单一和组合
                    if (strArray.Contains(processNodedt.Rows[0]["CC_Name"].ToString()))
                    {
                        ExecuteMatch(paragraphText, caseid, paragraphTypeId, processNodeName, processCCId, conditiondt);
                    }
                    else
                    {
                        ExecuteMatchOne(paragraphText, caseid, paragraphTypeId, processCCId, conditiondt);
                    }
                }
            }
            #endregion

            return true;
        }
        #endregion


        #region 单一规则
        /// <summary>
        /// 跑单一表述(单一的条件：符合本节点，则继续跑本节点的子节点，符合子节点，则本节点不挂。按此规则，循环递归跑完所有节点。)
        /// </summary>
        /// <param name="inputText">逻辑段内容</param>
        /// <param name="caseid">案例ID</param>
        /// <param name="paragraphTypeId">逻辑段类型ID</param>
        /// <param name="caseCauseId">ccId</param>
        /// <param name="conditiondt">ccid下的节点的范围</param>
        private void ExecuteMatchOne(string inputText, string caseid, string paragraphTypeId, string caseCauseId,
            DataTable conditiondt)
        {
            #region 变量
            string ccRegexInfoCode = "";
            string ccId = "";
            string ccName = "";
            int regCount = 0;
            int childCount = 0; 
            #endregion

            //查找规则下级
            DataRow[] arrayDr = conditiondt.Select("CC_ParentID='" + caseCauseId + "'");
            string listrccid ="";
            for (int j = 0; j < arrayDr.Length; j++) //第一级
            {
                #region 第一级规则详细信息
                ccRegexInfoCode = arrayDr[j]["CC_RegexInfoCode"].ToString();
                ccId = arrayDr[j]["CC_ID"].ToString();
                ccName = arrayDr[j]["CC_Name"].ToString();
                regCount = Convert.ToInt32(arrayDr[j]["RegCount"].ToString());
                childCount = Convert.ToInt32(arrayDr[j]["ChildCount"].ToString()); 
                #endregion
                Model.RuleNode model = new RuleNode();
                MatchChild_One(conditiondt, inputText, ccId, ccName, caseCauseId, ccRegexInfoCode, regCount, childCount
                     , ref listrccid);

                if (string.IsNullOrEmpty(listrccid.Trim()))
                    continue;
                AddMatchChild_One("",liMatch, paragraphTypeId, caseCauseId, listrccid);              
            }
        }
        /// <summary>
        /// 匹配子节点（非一层）
        /// </summary>
        /// <param name="conditiondt">节点树</param>
        /// <param name="oneinputText">逻辑段</param>
        /// <param name="ccId">当前节点ID</param>
        /// <param name="parentId">父节点ID</param>
        /// <param name="ccRegexInfoCode">正则编码</param>
        /// <param name="regCount">正则数量</param>
        /// <param name="childCount">子节点数量</param>
        /// <param name="resultText">结果ID字符串</param>
        /// <returns>子节点有匹配项，返回true，否则返回false</returns>
        public bool MatchChild_One(DataTable conditiondt, string oneinputText, string ccId, string ccname,string parentId,
            string ccRegexInfoCode, int regCount, int childCount,ref string listrccid)
        {
            int matchNumber = 0;
            Model.RuleNode model = new RuleNode();
            //没正则，默认不匹配
            //有正则
            if (regCount > 0)
            {
                matchNumber = IsMatch(oneinputText, ccRegexInfoCode);
                if (matchNumber == 1)
                {
                  
                    model.cc_id = ccId;
                    model.cc_name = ccname;
                    model.pcc_id = parentId;
                    model.regxStr = strMatch(oneinputText, ccRegexInfoCode);
                    liMatch.Add(model);
                    listrccid += "," + ccId;
                }
            }
            else //不匹配
            {
                return false;
            }

            #region  匹配

            if (matchNumber == 1) //匹配
            {
                bool child = false; //子级

                //判断当前节点的子节点是否存在匹配项
                //下级不为空
                if (childCount > 0)
                {
                    DataRow[] arrayDr = conditiondt.Select(" CC_ParentID='" + ccId + "' and CC_NodeType<>12 ");
                    for (int i = 0; i < arrayDr.Length; i++)
                    {
                        bool mat = MatchChild_One(conditiondt, oneinputText, arrayDr[i]["CC_ID"].ToString(), arrayDr[i]["CC_Name"].ToString(), ccId,
                            arrayDr[i]["CC_RegexInfoCode"].ToString(),
                            Convert.ToInt32(arrayDr[i]["RegCount"].ToString()),
                            Convert.ToInt32(arrayDr[i]["ChildCount"].ToString()), ref listrccid);
                        if (mat)
                        {
                            child = true;
                        }
                    }
                    if (!child)
                    {
                        return true;
                    }
                }
                return false;
            }

            #endregion

            //不匹配
            return false;
        }

        /// <summary>
        /// 递归添加
        /// </summary>
        /// <param name="allMsIdPid">要添加节点的所有父级</param>
        /// <param name="li">要添加的集合</param>
        public void AddMatchChild_One(string allMsIdPid, List<Model.RuleNode> li, string paragraphTypeId, string caseCauseId,string strliccid)
        {
            var itemccid = strliccid.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var Iccid in itemccid)
            {
                var item = li.Find(p => p.cc_id == Iccid);
                #region 节点属性
                int ismatch = 0; //民事没有构成不构成 todo by zhangpeng 2017-01-04

                bool affirmIdeaResultb = getregex.IsMatch("EI1601201151020001", item.cc_id);//true 认定不认定
                string affirmIdeaResult = affirmIdeaResultb ? "2" : "1";
                SYS_Express_MatchSituation stiuModel = new SYS_Express_MatchSituation
                {
                    IsMatch = ismatch,
                    MatchSource = "0",
                    AffirmIdeaResult = affirmIdeaResult,
                    AffirmIdeaSource = "0"
                };
                #endregion

                #region 第一步：添加SYS_Express_MatchSituation表
                string msId = "";
                msId = work.AddMatch(item.cc_id, item.pcc_id, item.cc_id, caseCauseId, stiuModel, allMsIdPid, false);
                if (string.IsNullOrEmpty(allMsIdPid))
                {
                    allMsIdPid = msId;
                }
                else
                {
                    allMsIdPid += "," + msId;
                } 
                #endregion
                #region 第二步：添加表述文本SYS_Express_Word_Process
                SYS_Express_Word wordModel = new SYS_Express_Word
                {
                    MS_ID = msId,
                    EW_CaseId = item.caseid,
                    EW_Content = item.regxStr,
                    EW_UseCount = 1,
                    EW_WordCount = item.regxStr.Length,
                    ParagraphTypeId = Convert.ToInt32(paragraphTypeId)
                };
                wordModel.EW_ID = wordbll.Exists_WordProcess(wordModel);

                if (wordModel.EW_ID == "")
                {
                    wordModel.EW_ID = newid.JudgeDoc_CreateID("SYS_Express_Word");
                    wordModel.EW_Right = 0;
                    wordModel.EW_Wrong = 0;
                    wordModel.UpdateTime = DateTime.Now;
                    wordbll.AddWord_Process(wordModel);
                }
                else
                {
                    wordModel.UpdateTime = DateTime.Now;
                    wordbll.UpdateWord_Process(wordModel);
                }
                #endregion
            }
        }
        #endregion

        #region 单一与组合混合
        #region 具体匹配方法
        /// <summary>
        ///  循环递归规则处理案例
        /// </summary>
        /// <param name="inputText">匹配文章</param>
        /// <param name="caseid">案例id</param>
        /// <param name="processNodeName">规则名称</param>
        /// <param name="processCCId">规则id</param>
        /// <param name="conditiondt">条件</param>
        /// <param name="conditiondt">是否包含本节点</param>
        public void ExecuteMatch(string inputText, string caseid,string paragraphTypeId, string processNodeName, string processCCId,
        DataTable conditiondt)
        {
            #region 变量
            string ccRegexInfoCode = "";
            string ccId = "";
            string ccName = "";
            int regCount = 0;
            int childCount = 0; 
            #endregion
            //符合规则节点下的第一级子节点
            DataRow[] arrayDr = conditiondt.Select("CC_ParentID='" + processCCId + "'");
            string resultid = ""; //返回匹配的ccid集合
            for (int j = 0; j < arrayDr.Length; j++) //第一级
            {
                outMatch = new List<string>();
                liMatch = new List<RuleNode>();
                #region 要匹配的节点信息
                ccRegexInfoCode = arrayDr[j]["CC_RegexInfoCode"].ToString();
                ccId = arrayDr[j]["CC_ID"].ToString();
                ccName = arrayDr[j]["CC_Name"].ToString();
                regCount = Convert.ToInt32(arrayDr[j]["RegCount"].ToString());
                childCount = Convert.ToInt32(arrayDr[j]["ChildCount"].ToString());
                #endregion
                MatchChild(conditiondt, inputText, ccId, ccName, processCCId, ccRegexInfoCode, regCount, childCount,
                     caseid, ref resultid);
                if (string.IsNullOrEmpty(resultid.Trim()))
                    continue;

                #region 处理返回的数据

                AddZuhe(liMatch, "", processCCId, paragraphTypeId, resultid);
                #endregion

            }
        }
        /// <summary>
        ///  匹配规则
        ///  1。首先判断正则数目 （小于等于0 return 0）
        ///  2：有正则，并且匹配 （不匹配 return 0）
        ///  3：查找规则子集。并且调用MatchChild_One (知道最后一级别。因为1条件 返回)
        /// </summary>
        /// <param name="conditiondt"></param>
        /// <param name="oneinputText">要匹配的文本</param>
        /// <param name="ccId">要匹配的案由ID</param>
        /// <param name="parentId">要匹配的案由父级ID</param>
        /// <param name="ccRegexInfoCode">正则code</param>
        /// <param name="regCount">正则数量</param>
        /// <param name="childCount">案由子集节点树</param>
        /// <param name="resultid">返回的匹配的id(从最高级到最低级)</param>
        /// <returns></returns>
        public bool MatchChild(DataTable conditiondt, string oneinputText, string ccId,string ccname, string parentId,
    string ccRegexInfoCode, int regCount, int childCount, string caseid,ref string listrccid) //CC_ID 及以下是不是有匹配
        {
            int matchNumber = 0; //判断传过来的规则结束是否匹配
            Model.RuleNode chmodel = new RuleNode();
            #region 有正则,进行数据匹配
            if (regCount > 0)
            {
                matchNumber = IsMatch(oneinputText, ccRegexInfoCode);
                if (matchNumber > 0)
                {
                    chmodel.cc_id = ccId;
                    chmodel.cc_name = ccname;
                    chmodel.pcc_id = parentId;
                    chmodel.regxStr = strMatch(oneinputText, ccRegexInfoCode);
                    chmodel.caseid = caseid;
                    liMatch.Add(chmodel);
                    if (childCount > 0)
                    {
                        listrccid += "," + ccId;
                    }
                }
            }
            else //不匹配
            {
                listrccid += ";";
                return false;
            } 
            #endregion

            #region  匹配成功
            if (matchNumber == 1) //匹配
            {
                bool child = false; //子级
                #region 递归匹配
                #region 下级不为空递归匹配
                if (childCount > 0)
                {
                    DataRow[] arrayDr = conditiondt.Select(" CC_ParentID='" + ccId + "' and CC_NodeType<>12 ");
                    for (int i = 0; i < arrayDr.Length; i++)
                    {
                        if (outMatch.Contains(ccId))
                        {
                            continue;
                        }
                        if (!outMatch.Exists(p => p == arrayDr[0]["CC_ID"].ToString())) // 组合匹配，剔除组合匹配的数据
                        {
                            bool mat = MatchChild(conditiondt, chmodel.regxStr, arrayDr[i]["CC_ID"].ToString(), arrayDr[i]["CC_Name"].ToString(), ccId,
                                arrayDr[i]["CC_RegexInfoCode"].ToString(),
                                Convert.ToInt32(arrayDr[i]["RegCount"].ToString()),
                                Convert.ToInt32(arrayDr[i]["ChildCount"].ToString()),caseid, ref listrccid);
                            if (mat)
                            {
                                child = true;
                            }
                        }
                    }
                }
                #endregion
                #region 没有下级，进行组合匹配
                else //如果没有子集，到了最后一级
                {
                    
                    /*
                    * 下级为空，则该节点为最小节点，开始判断该节点的父节点的同级节点是否匹配，如果匹配，则继续匹配同级节点的子节点
                    */
                    DataRow[] arrayDr = conditiondt.Select("CC_ID='" + parentId + "'");
                    var ccIdGrandParentId = arrayDr[0]["CC_ParentID"].ToString();
                    bool b1 = false;
                    if (!outMatch.Exists(p => p == arrayDr[0]["CC_ID"].ToString())) //只有父结点在争议节点要素下
                    {
                        // 如果存在组合，设置节点属性为组合
                        b1 = MatchSiblingsNode(conditiondt, oneinputText, parentId, ccIdGrandParentId, ccname, chmodel);
                    }
                    if (b1)
                    {
                        listrccid += "," + ccId + ",组合;";
                    }
                    else
                    {
                        listrccid += "," + ccId + ";"; //每条支路
                    }
                    return true;
                }
                #endregion
                #endregion
                if (!child) //传过来的节点匹配了,下级没有匹配到(没写数据不挂数据)
                {
                    return true;
                }
                return false;
            }

            #endregion

            //不匹配
            return false;
        }
        #endregion

        /// <summary>
        /// 匹配同级节点及子节点
        /// </summary>
        /// <param name="conditiondt">跑表述的节点集合</param>
        /// <param name="oneinputText">表述逻辑段</param>
        /// <param name="ccId">当前节点（表述符合正则规则）</param>
        /// <param name="ccIdParentId">当前节点的父节点ID</param>
        /// <param name="ccIdChildId">当前节点的子节点ID</param>
        /// <param name="matchSiblingsIdList">匹配的同级节点集合</param>
        /// <returns>是否存在匹配的同级节点，存在，则返回true，否则返回false</returns>
        ///                     var siblingsResult = MatchSiblingsNode(conditiondt, oneinputText, ccIdParentId, ccIdGrandParentId, ccId, ccName, siblingsList, matchsSiblingsNodes);
        private bool MatchSiblingsNode(DataTable conditiondt, string oneinputText, string ccId, string ccIdParentId, string ccName,
           Model.RuleNode model)
        {

            bool isMatchSiblings = false;
            if (conditiondt != null && conditiondt.Rows.Count > 0)
            {
                //获取当前节点的同级节点,不包括当前节点
                var arrayDr =
                    conditiondt.Select("CC_ParentID='" + ccIdParentId + "' and CC_NodeType<>12 and CC_ID <> '" + ccId + "'");
                //不存在同级节点
                if (!arrayDr.Any())
                    return isMatchSiblings;
                else
                {
                    #region 循环同级节点，查看是否匹配，匹配则继续匹配同级节点的子节点
                    for (var i = 0; i < arrayDr.Length; i++)
                    {
                        #region 外侧代码
                        var currentId = arrayDr[i]["CC_ID"].ToString();
                        var currentCcIdName = arrayDr[i]["CC_Name"].ToString();
                        var regexInfoCode = arrayDr[i]["CC_RegexInfoCode"].ToString();
                        var regexCount = Convert.ToInt32(arrayDr[i]["RegCount"].ToString()); 
                        #endregion

                        //同级节点有正则且匹配，则判断是否匹配该节点的子节点
                        if (regexCount > 0 && IsMatch(oneinputText, regexInfoCode) == 1)
                        {
                            var childDr = conditiondt.Select("CC_ParentID='" + currentId + "'");
                            if (!childDr.Any())
                                continue;
                            //匹配子节点,默认只取子节点的第一个，按照案例加工人员创建节点树的规则，在这个节点下是不会有两个子节点的
                            var currentChildId = childDr[0]["CC_ID"].ToString();
                            var childRegexInfoCode = childDr[0]["CC_RegexInfoCode"].ToString();
                            var childName = childDr[0]["CC_Name"].ToString();
                            var childRegexCount = Convert.ToInt32(arrayDr[i]["RegCount"].ToString());

                            //该节点存在正则，表述匹配正则，节点名称与源节点的子节点名称相等
                            if (childRegexCount > 0 && IsMatch(oneinputText, childRegexInfoCode) == 1 && childName.Contains(ccName))
                            {
                                // 存在，则修改父级节点名称，及其状态
                                var Pmodel = liMatch.Find(p => p.cc_id == model.pcc_id);
                                if (Pmodel != null)
                                {
                                    liMatch.Remove(liMatch.Where(p=>p.cc_id == Pmodel.cc_id).FirstOrDefault());
                                    Pmodel.isdouble = true;
                                    Pmodel.cc_name += "+" + currentCcIdName;
                                    Pmodel.pcc_id += "," + currentChildId; 
                                    liMatch.Add(Pmodel);
                                    outMatch.Add(currentId);
                                    isMatchSiblings = true;
                                }
                            }
                        }
                    } 
                    #endregion

                    return isMatchSiblings;
                }

            }
            return isMatchSiblings;

        }

        #region 循环递归添加
        public void AddZuhe(List<Model.RuleNode> li, string allMsIdPid, string caseCauseId, string paragraphTypeId,string strliccid)
        {
            var liccids = strliccid.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); // 获取匹配的ccid 集合
            foreach (var itemli in liccids)
            {
                bool b1 = itemli.Contains("组合");
                if (b1)
                {
 
                }
                string ss = itemli.Replace(",组合", "").ToString();
                var liccid = ss.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                string pid = "";
                foreach (var ItemccId in liccid)
                {
                    if (outMatch.Exists(p => p == ItemccId))
                    {
                        continue;
                    }
                    else
                    {
                        var item = li.Find(p => p.cc_id == ItemccId); // 在结合中找到要插入的model
                        if (item == null)
                        {
                            continue;
                        }

                        #region 节点属性
                        int ismatch = 0; //民事没有构成不构成 todo by zhangpeng 2017-01-04

                        bool affirmIdeaResultb = getregex.IsMatch("EI1601201151020001", item.regxStr);//true 认定不认定
                        string affirmIdeaResult = affirmIdeaResultb ? "2" : "1";
                        SYS_Express_MatchSituation stiuModel = new SYS_Express_MatchSituation
                        {
                            IsMatch = ismatch,
                            MatchSource = "0",
                            AffirmIdeaResult = affirmIdeaResult,
                            AffirmIdeaSource = "0"
                        };
                        #endregion

                        #region 第一步：添加SYS_Express_MatchSituation表
                        string msId = "";
                        if (!b1)
                        {
                            if (string.IsNullOrEmpty(pid))
                            {
                                pid = "S" + item.pcc_id;
                                
                            }
                            msId = work.AddMatch(item.cc_id, pid, item.cc_id, caseCauseId, stiuModel, allMsIdPid, false);
                        }
                        else
                        {
                            if (string.IsNullOrEmpty(pid))
                            {
                                pid = "M" + item.pcc_id;
                            }
                            msId = work.AddCivilMatch(item.cc_id,item.cc_name,pid, item.cc_id, caseCauseId, stiuModel, allMsIdPid);
                        }
                        pid = msId;
                        if (string.IsNullOrEmpty(allMsIdPid))
                        {
                            allMsIdPid = msId;
                        }
                        else
                        {
                            allMsIdPid += "," + msId;
                        }
                        #endregion
                        #region 第二步：添加表述文本SYS_Express_Word_Process
                        SYS_Express_Word wordModel = new SYS_Express_Word
                        {
                            MS_ID = msId,
                            EW_CaseId = item.caseid,
                            EW_Content = item.regxStr,
                            EW_UseCount = 1,
                            EW_WordCount = item.regxStr.Length,
                            ParagraphTypeId = Convert.ToInt32(paragraphTypeId)
                        };
                        wordModel.EW_ID = wordbll.Exists_WordProcess(wordModel);

                        if (wordModel.EW_ID == "")
                        {
                            wordModel.EW_ID = newid.JudgeDoc_CreateID("SYS_Express_Word");
                            wordModel.EW_Right = 0;
                            wordModel.EW_Wrong = 0;
                            wordModel.UpdateTime = DateTime.Now;
                            wordbll.AddWord_Process(wordModel);
                        }
                        else
                        {
                            wordModel.UpdateTime = DateTime.Now;
                            wordbll.UpdateWord_Process(wordModel);
                        }
                        #endregion

                    }
                }
            }
        }
        #endregion
        #endregion

        #region 正则是否匹配
        /// <summary>
        /// 正则是否匹配
        /// </summary>
        /// <param name="inputText">逻辑段</param>
        /// <param name="ccRegexInfoCode">正则单元</param>
        /// <returns></returns>
        public int IsMatch(string inputText, string ccRegexInfoCode)
        {
            try
            {
                if (getregex.IsMatch(ccRegexInfoCode, inputText))//匹配 CC_RegexInfoCode为编号
                {
                    return 1;
                }
                else
                {
                    return 0;
                }
            }
            catch (Exception)
            {

                return 0;
            }


        }
        /// <summary>
        ///  获取匹配机关
        /// </summary>
        /// <param name="inputText">文本</param>
        /// <param name="ccRegexInfoCode">逻辑段code</param>
        /// <returns>string 文本</returns>
        public string strMatch(string inputText, string ccRegexInfoCode)
        {
            try
            {
                return getregex.GetParseValue(ccRegexInfoCode, inputText);
            }
            catch (Exception)
            {

                return "";
            }
        }
        #endregion


        public void Addmodels(Model.RuleNode Pmodel, Model.RuleNode addmodel, string Pcc_id)
        {
            foreach (var item in Pmodel.liCH)
            {
                if (item.liCH == null && item.liCH.Count > 0)
                {
                    continue;
                }
                if (item.cc_id == Pcc_id)
                {
                    item.liCH = new List<RuleNode>();
                    item.liCH.Add(addmodel);
                }
                else
                {
                    Addmodels(item, addmodel, Pcc_id);
                }
            }
        }


    }
}
